<!-- 登录 -->
<template>
	<view class="login" v-if="is_init">
		<view class="title">
			<p>登录</p>
		</view>
		<view class="input-box">
			<view class="input ui-1px-b">
				<p>手机号</p>
				<view class="bottom x-c">
					<input type="number" placeholder="请填写手机号" v-model="form.mobile"
						placeholder-style="color:#999;font-weight: 500;font-size: 28rpx;" />
					<view class="get_sms" @click="get_sms" v-if="show">
						<v-button class="red" :plain="false" :throttle-time="60000" :custom-style="customStyle">
							获取验证码
						</v-button>
					</view>
					<view class="gray" v-if="changeBtn">
						<span>({{ count }}s)</span>
					</view>
				</view>
			</view>
			<view class="input ui-1px-b">
				<p>验证码</p>
				<view class="sms">
					<input type="number" placeholder="请填写验证码" v-model="form.smscode"
						placeholder-style="color:#999;font-weight: 500;font-size: 28rpx;" style="padding-top: 36rpx;" />
				</view>
			</view>
		</view>
		<view class="btn">
			<button @click="login">登陆</button>
		</view>
		<view class="agreement">
			<view class="agreement_btn">
				<view class="circle" @click.stop="show_show" :class="{'change_circle' : showbtn}"></view>
			</view>
			<p>
				新用户登录即自动注册，并表示已同意
				<span class="red" @click="jumpUser">《用户服务协议》</span>
			</p>
		</view>
	</view>
</template>
<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	export default {
		data() {
			//这里存放数据
			return {
				key: null,              				 // 存放共享积分的key
				userInfo: {},							 // 初始化会员信息
                user: {},              					 // 初始化会员信息
				wx_ico: this.imgUrl + 'wx.png',  		 // 微信logo图片
				show: true,								 // 验证码显示
				showbtn: false,                          // 用户协议样式状态
				is_init: false,							 // 判断是否登入
				customStyle: {							 // 验证码样式
					fontSize: "24rpx", 
					color: '#FF5445'
				},
                click: 0,               				 // 防止多次点击
				changeBtn: false, 						 // 显示秒状态
				count: 60,								 // 倒计时
				timer: null,							 // 计时器
				form: { 								 // 用户表单
					mobile: '',
					smscode: ''
				},
				smscode: '',							 // 验证码
				rule: {									 // 正则校验
					mobile: {
						type: "form_data",
						rules: [{
								rule: /^[1][3-9][0-9]{9}$/,
								v_res: true,
								message: "请填写正确的手机号码",
							},
							{
								rule: /^s*$/,
								v_res: false,
								message: "请填写手机号",
							},
						],
					},
					smscode: {
						type: "form_data",
						rules: [{
							rule: /^s*$/,
							v_res: false,
							message: "请填写验证码",
						}, ],
					},
					obj: {}   ,
					orderId: 0 ,// 订单id
					is_group: 0 // 团购订单
				},
			};
		},
		computed: {
			...mapState({
				info: state => state.member.info,   // 用户初始化信息
			})
		},
		onLoad(option) {
            // 如果进入程序时有携带参数，则进行请求后端。
			let that = this;
			let params = getCurrentPages()[0].options;
				if (params != undefined && JSON.stringify(params) != '{}') {
				 that.key = params.key
				 that.orderId = params.order_no
				 that.is_group = params.is_group
				 that.obj = {
				  key: that.key,
				  orderId: that.orderId
				 }
			}
			this.getLogin();
			console.log(that.orderId,'that.orderId')
			console.log(params,'params')
		},
		//方法集合
		methods: {
			// 登入
			getLogin() {
				let that = this;
				uni.login({
					provider: 'weixin',
					success(res) {
						let obj = { code: res.code }
						that.$api('auth.wxAuthLogin', obj).then(data => {
							that.$store.dispatch('member/get_info', data.data);
							if (data.data.is_login) {
								if (that.key) {
									// 共享积分页面 -  
									that.$Router.replace ({
										path: '/pages/user/score/share/getShare/index',
										query: { key: that.key }
									})
									return;
								}
								// 判断是否有订单id，则跳转订单详情
								console.log('跳转详情前')
								if(that.orderId) {
									console.log('跳转详情完')
									// 判断是否团购订单
									if(that.is_group == '1') {
										console.log('团购')
										that.$api('orderinfoGroup', {
											order_no: that.orderId
										}).then(res => {
											let arr = res;
											arr.data.group_submit_time = that.$tools.time_data(arr.data.group_submit_time, 'double')
											arr.data.group_validity_time = that.$tools.time_data(arr.data.group_validity_time,
												'double')
											arr.data.submit_time = that.$tools.time_data(arr.data.submit_time, 'double')
											that.$store.dispatch('order/get_orderDetail', arr.data)
										})
										that.$Router.replace ({
											path: '/pages/user/order/detail/index'
										})
									}
									if(that.is_group == '0') {
										console.log('非团购')
										// 订单详情页面 -
										that.$api('orderinfo', {
											order_no: that.orderId
										}).then(res => {
											let arr = res
											arr.data.submit_time = that.$tools.time_data(arr.data.submit_time, 'double')
											that.$store.dispatch('order/get_orderDetail', arr.data)
										})
										that.$Router.replace ({
											path: '/pages/user/order/detail/index'
										})
										console.log('跳转成功')
									}
									return;
								}
								that.$Router.replace ({
									path: '/pages/home_index/home_index'
								})
							} 
							else if (!data.data.is_login) {
								that.is_init = true;
							}
						})
					}
				})
			},
			jumpUser() {
				this.$tools.toast('暂无用户协议')
				return;
				this.$Router.push({
					path: '/pages/login/agreement/index'
				})
			},
			show_show() {
				if (this.showbtn) {
					this.showbtn = false;
				} else {
					this.showbtn = true;
				}
			},
			/**
			 *  判断首页登录信息 - 给后台发送code信息， 如验证已登录则跳转至首页。
			 *  否则进行登录。
			 */
			get_sms() {
				if (!this.form.mobile.length) {
					this.$tools.toast('请输入手机号')
					return
				}
				if (this.form.mobile.length > 11 || this.form.mobile.length < 11) {
					this.$tools.toast('请输入正确的手机号')
					return
				}
				this.show = false;
				clearInterval(this.timer);
				this.count = 60;
				this.changeBtn = !this.changeBtn;
				this.timer = setInterval(() => {
					this.count = this.count - 1;
					if (this.count < 1) {
						this.changeBtn = !this.changeBtn;
						// 停止倒计时
						clearInterval(this.timer);
						this.timer = null;
						this.count = 60;
						this.show = true;
					}
				}, 1000);
				// 获取验证码
				let obj = {
				    mobile: this.form.mobile
				}
				this.$api('auth.getSMS', obj).then(res => {
				    this.smscode = res.status;
				})
			},
			login() {
			    let that = this;
			    // 判断 短信验证码的返回值是否为1, 如果未点击 或者 未获取成功，则提示用户;658406
			    if (!that.smscode) {
			        that.$tools.toast('请获取验证码');
			        return;
			    }
			    // 判断 如果已经点击过一次 则 直接返回;
			    if (that.click) return;
			    /**
			    * 验证 输入的手机号，验证码是否符合要求；
			    * 手机号 十一位， 验证码为纯数字 且 长度为六位;
			    */
			    let status = that.$tools.verification(that.form, that.rule)
			    if (!status.status) return;
			    if (!that.showbtn) {
			        that.$tools.toast('请同意用户服务协议');
			        return;
			    }
			    if (that.form.smscode.length != 6) {
			        that.$tools.toast('请输入6位的验证码');
			        return;
			    }
			    // 构造请求参数
			    let submit = {
			        openid: that.info.openid,
			        mobile: that.form.mobile,
			        code: that.form.smscode
			    }
			    that.click++;
			    /**
			    * 请求登陆接口， 验证成功之后拉起授权界面；
			    * 授权成功 调取初始化接口 - 可改完获取会员信息接口;
			    */
			    that.$api('auth.submit', submit).then(res => {
			        that.click = 0;
			        let data = res;
			        wx.getUserProfile({
			            desc: '用于完善会员资料',
			            success: (res) => {
			                let userInfo = res.userInfo;
			                that.UserInfo = res.userInfo;
			                if (data.data != '') {
			                    that.$store.dispatch('member/get_info_id', data.data)
			                    that.init(data.data);
			                }
			                if (!that.info.member_id) {
			                    that.$store.dispatch('member/get_info_id', data.data);
			                }
			            }
			        })
			    }).catch(e => {
			        that.click = 0;
			    })
			},
			init(member_id) {
			    let that = this;
				if (that.key != null) {
				    that.$Router.replace({
				        path: '/pages/user/score/share/getShare/index',
						query: { key: that.key }
				    })
				} else {
					this.$api('init', {
					    member_id
					}).then(res => {
					   let data = res.data;
					   that.user = data.memberInfo;
					   if (!that.user.nickName) {
					      let obj = {
					          nickname: that.UserInfo.nickName,
					          gender: that.UserInfo.gender,
					          pic_url: that.UserInfo.avatarUrl
					      }
					      this.$api('memberupdateInfo', obj).then(res => {
					          if (res.status === 1) {
					              that.$Router.replace({
					                  path: '/pages/home_index/home_index'
					              })
					          }
					      })
					   } else {
					       that.$Router.replace({
					           path: '/pages/home_index/home_index'
					       })
					   }
					})
				}
			},
		},
	};
</script>
<style lang='scss' scoped>
	@import './index.scss';

	.change_circle {
		background-image: url('/static/image/common_ic_12_selected.png');
		background-repeat: no-repeat;
		background-position: center;
		background-size: 50rpx 50rpx;
		border: none !important;
	}
</style>
<style>
	page {
		background-color: #fff;
	}
</style>
